package com.ymatou.iapi.socketio;


import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;
import java.util.Set;



















import net.sf.json.JSONSerializer;

import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.commons.lang3.tuple.Pair;


import org.apache.http.client.ClientProtocolException;
import org.json.JSONException;
import org.json.JSONObject;

import com.google.gson.JsonObject;
import com.ymatou.iapi.csim.parameter.SendMessageBean;
import com.ymatou.iapi.pushbind.parameter.BindUserClientBean;
import com.ymatou.iapi.pushbind.parameter.Enum.AppIdType;
import com.ymatou.iapi.pushbind.parameter.Enum.PhoneType;
import com.ymatou.iapi.pushbind.parameter.Enum.UserSystemType;
import com.ymatou.iapi.socketio.parameter.pushBean;
import com.ymatou.iapi.socketio.service.pushCall;
import com.ymatou.iapi.userregister.parameter.UserRegisterInfoRequestDtoBean;
import com.ymatou.iapi.userregister.service.UserRegisterInfoRequestDtoCall;
import com.ymt.core.tool.Logger;
import com.ymttest.business.data.socket.DefaultSocketIo;
import com.ymttest.business.data.socket.SocketIoConnection.Listener;
import com.ymttest.business.service.CsimCallService;
import com.ymttest.business.service.ImCallService;
import com.ymttest.business.service.JUserCallService;
import com.ymttest.business.service.PushCallService;
import com.ymttest.database.model.ymt_onlinecs;
import com.ymttest.database.redis.ImRedisWapper;
import com.ymttest.database.sqlwapper.ImDefaultWapper;
import com.ymttest.utils.TestDataManager;
import com.ymttest.utils.YMTDateUtil;

public class socketio_stress {

	private SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
	private String messageBody=df.format(new Date()); 
	private  static SimpleDateFormat df2 = new SimpleDateFormat("yyyyMMddHHmmss");//设置日期格式
	private SimpleDateFormat df3 = new SimpleDateFormat("yyyy-MM-dd");//设置日期格式
	//登录时绑定
	public  Pair<Integer, String> BindUserClient(Integer userId,String clientId) throws IOException
	{
		BindUserClientBean bindUserClientBean=PushCallService.intitUserClient(userId);
		bindUserClientBean.setAppId("s1.ymatou.com");
		bindUserClientBean.setUserSystemType(UserSystemType.CsUser);
		bindUserClientBean.setAppIdType(AppIdType.SocketIo);
		bindUserClientBean.setPhoneType(PhoneType.All);
		bindUserClientBean.setClientId(clientId);
		PushCallService.bindUserClient(bindUserClientBean);
		Pair<Integer, String> UserIdAndClientId =Pair.of(userId, bindUserClientBean.getClientId());
		return UserIdAndClientId;
	}
	
	public  Integer sendMsg() throws ClientProtocolException, IOException
	{
		UserRegisterInfoRequestDtoBean regbean = JUserCallService.initUserRegisterInfoRequestDtoBean();
		UserRegisterInfoRequestDtoCall urrc = JUserCallService.UserRegisterInfoRequestDtoCall(regbean);
		JsonObject registerResult = urrc.getJsonObject().get("Result").getAsJsonObject();
		String token = registerResult.get("Token").getAsString();
		Integer userId = urrc.getUserid();
		CsimCallService service=new CsimCallService();
		SendMessageBean sendMessageBean=service.setSendMessageBean();
		sendMessageBean.setMessage("socket用户 给客服发消息_"+TestDataManager.getRandomIntNum(5));
		sendMessageBean.setUserId(userId);
		service.setSendMessageCall(sendMessageBean);
		return userId;
	}
	//SocketIoPush 发送消息到 Soslave
	public  String SocketIoPush(Integer fromId,Integer touserId) throws ClientProtocolException, IOException, InterruptedException
	{
		CsimCallService service=new CsimCallService();
		ymt_onlinecs onlinecs=service.getOnlineCS(touserId);
		
		String msg="{\"fromid\":"+fromId+",\"toid\":"+touserId+",\"msg\":\""+messageBody+"\",\"mustreceive\":\"0\"}";
		pushBean pushbean=new pushBean();
		pushCall pushcall=new pushCall();
		
		pushbean.setuserId(touserId);
		pushbean.setmessageBody(msg);
		pushcall.setData(pushbean);
		pushcall.callService();
		return msg;
	}
	
	
	public void scalTime(String date) throws ClientProtocolException, IOException, InterruptedException ,NumberFormatException, ParseException
	{
		UserRegisterInfoRequestDtoBean regbean = JUserCallService.initUserRegisterInfoRequestDtoBean();
		UserRegisterInfoRequestDtoCall urrc = JUserCallService.UserRegisterInfoRequestDtoCall(regbean);
		Integer userId = urrc.getUserid();
		String clientId = String.valueOf((500000 + new Random().nextInt(1000000)));
		DefaultSocketIo socketIo=new DefaultSocketIo("http://172.16.101.73:8085");//soslave.ymatou.com	
		
		socketIo.addLinstner("receivemsg",new Listener() {
            public void call(Object... args) throws JSONException {
            	System.out.println("args[0]："+args[0]);
				if(args[0].toString().contains(df3.format(new Date()).toString()))
				{
					JSONObject jsonObject = new JSONObject(args[0].toString() );
					long sendTime=Long.parseLong(jsonObject.getString("sendtime"));
					long accpetTime=new Date().getTime();
					long scalTime=accpetTime-sendTime;
					TestDataManager.appendFileToLine("E:\\time\\scalTime"+date+".txt", String.valueOf(scalTime));

					System.out.println("time:"+String.valueOf(scalTime));
				}
            }
        });//soslave接收消息
		
		socketIo.connect();
		//Thread.sleep(2000);
		socketIo.emit("guid", clientId);//soslave发送消息
		socketio_stress s=new socketio_stress();	
		s.BindUserClient(userId,clientId);
		
		Integer cs_userId=s.sendMsg();//买家或者买手 发消息 给客服发消息
		String msg=s.SocketIoPush(cs_userId,userId);//socketIoPush 给 soslave 发送消息
		System.in.read();
	}

	
	public static void main(String[] args) throws ClientProtocolException, IOException, InterruptedException, NumberFormatException, JSONException, ParseException  {

		//#######测试开始
		String date=df2.format(new Date());
		socketio_stress s=new socketio_stress();
//		s.scalTime(date);
//		System.out.println("测试:"+args[0]);
		//#######测试结束

		// 同时启动1000个线程，去进行i++计算，看看实际结果
		if(args.length>0){
			 for (int i = 0; i <args.length; i++) {
			    new Thread(new Runnable() {
			         @Override
			        public void run() {
			        	 try {
			        		 try {
								s.scalTime(date);
							} catch (NumberFormatException e) {
								e.printStackTrace();
							} catch (ParseException e) {
								e.printStackTrace();
							}
						} catch (IOException | InterruptedException e) {
							e.printStackTrace();
						} 
			         }
			     }).start();
			 }
		}
//		 
//    	ArrayList<String> list=TestDataManager.getLines("E:\\time\\scalTime"+date+".txt");
//    	if(list.size()+100>Integer.parseInt(args[0])){
//			long sum_time=0;
//			for(String t:list)
//			{
//				sum_time+=Long.parseLong(t);
//			}
//			TestDataManager.appendFileToLine("E:\\time\\AvgTime"+date+".txt", String.valueOf((sum_time/list.size())));
//    	}
//    	else
//    		Thread.sleep(3000);
    	
    	
    	
    	
    	
    	
    	
    	
    	
    	
    	
    	
    	
    	
    	

//    	long sendTime=Long.parseLong(jsonObject.getString("sendtime"));
//    	long accpetTime=new Date().getTime();
//    	long scalTime=accpetTime-sendTime;
//    	System.out.println("time:"+scalTime);  	
		
//		String str="{\"fromid\":\"dbc60cc2-5f7c-41d7-a139-9e931fd7a98a\",\"toid\":\"1073463\",\"uuid\":\"C845BE3E-A3B0-0001-34D0-67F1DC301816\",\"msg\":{\"UserId\":24812472,\"ToUserId\":24812849,\"MessageType\":0},\"sendtime\":1545973679676,\"mustreceive\":\"0\"}";		
//		JSONObject jsStr = new JSONObject(str);		
//		System.out.println(jsStr.get("sendtime"));
		
	


	}
	 //  socketIo.emit("sendmsg", msg);//socketIoPush 给工作平台 发送消息		
//	ImRedisWapper imRedis=new ImRedisWapper();
//	Set<String> redis_str=imRedis.getBindUserRedis("BindRecord:UserBindSet:1:"+userId);
//	System.out.println("redis_str:"+redis_str.toString());
}

